﻿using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Model;

namespace TaxiDispatchClient
{
    public partial class TaxiForm : DevExpress.XtraEditors.XtraForm
    {
        public TaxiForm()
        {
            InitializeComponent();
        }

        private Thread _thread;
        private bool _isLoad;
        private bool _isAdd;


        private void TaxiForm_Load(object sender, EventArgs e)
        {
  

            _isLoad = true;
            _thread = new Thread(BindGrid);
            _thread.Start();
        }
         
      
        private void BindGrid()
        {
            try
            {
                
                string parameterVaule = textEdit_condition.Text.Trim();
                string parameter = "t.PhoneNumber";
                switch (radioGroup_SelectType.SelectedIndex)
                {
                    case 0:
                        parameter = "t.PhoneNumber";
                        break;
                    case 1:
                        parameter = "TaxiNo";
                        break;                    
                }
                
                StringBuilder strWhere = new StringBuilder();
                if (parameterVaule != "")
                { 
                    strWhere.Append(parameter);
                    strWhere.Append(" like '%");
                    strWhere.Append(parameterVaule);
                    strWhere.Append("%' ");                                
                }
                DataSet ds = MainForm.PositionService.TaxiGetList(strWhere.ToString());

                if (ds != null && ds.Tables.Count == 1)
                {
                    ClearInputControl();
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        switch (row["State"].ToString())
                        {
                            case "0":
                                row["State"] = "待分配";
                                break;
                            case "1":
                                row["State"] = "跑班中";
                                break;
                            case "2":
                                row["State"] = "休假中";
                                break;
                        }
                 
                    }
                  
                    BeginInvoke(new MethodInvoker(() =>
                    {

                        gridControl1.DataSource = ds.Tables[0];
                        gridView1.GroupPanelText = "司机列表-共" + ds.Tables[0].Rows.Count + "位";
                         
                        if (_isAdd)
                        {
                            gridView1.FocusedRowHandle = gridView1.RowCount - 1;
                            _isAdd = false;
                        }                      
                        btn_select.Enabled = true;
                    }));
                }
                   
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);
                //  BeginInvoke(new MethodInvoker(() => btn_select.Enabled = true));               
            }
        }
 

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);//
            if (row != null)
            {
                label_id.Text = row["id"].ToString();
                textEdit_TaxiNo.Text = row["TaxiNo"].ToString();
                textEdit_TaxiType.Text = row["TaxiType"].ToString();
                textEdit_PhoneNumber.Text = row["PhoneNumber"].ToString();
                textEdit_remark.Text = row["Remark"].ToString();               
                textEdit_Imei.Text = row["IMEI"].ToString();
                switch (row["State"].ToString())
                {
                    case "待分配":
                        comBox_statelist.SelectedIndex = 0;
                        break;
                    case "跑班中":
                        comBox_statelist.SelectedIndex = 1;
                        break;
                    case "休假中":
                        comBox_statelist.SelectedIndex = 2;
                        break;
                }
                btn_modify.Enabled = true;
            }
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);//
            if (row != null)
            {
                label_id.Text = row["id"].ToString();
                textEdit_TaxiNo.Text = row["TaxiNo"].ToString();
                textEdit_TaxiType.Text = row["TaxiType"].ToString();
                textEdit_PhoneNumber.Text = row["PhoneNumber"].ToString();
                textEdit_remark.Text = row["Remark"].ToString();
                textEdit_Imei.Text = row["IMEI"].ToString();
                switch (row["State"].ToString())
                {
                    case "待分配":
                        comBox_statelist.SelectedIndex = 0;
                        break;
                    case "跑班中":
                        comBox_statelist.SelectedIndex = 1;
                        break;
                    case "休假中":
                        comBox_statelist.SelectedIndex = 2;
                        break;
                }
                btn_modify.Enabled = true;
            }
        }


        private void simpleButton_add_Click(object sender, EventArgs e)
        {
            if (btn_add.Tag.ToString() == "新增")
            {
                label_id.Text = "";
                textEdit_PhoneNumber.Text = "";
                textEdit_Imei.Text = "";
                textEdit_TaxiNo.Text = "";
                textEdit_TaxiType.Text = "";
                textEdit_remark.Text = "";
                comBox_statelist.SelectedIndex = 0;

                textEdit_PhoneNumber.Enabled = true;
                textEdit_Imei.Enabled = true;
                textEdit_TaxiNo.Enabled = true;
                textEdit_TaxiType.Enabled = true;
                textEdit_remark.Enabled = true;
                comBox_statelist.Enabled = true;
                
                gridControl1.Enabled = false;
                btn_select.Enabled = false;
                btn_modify.Visible = false;
                btn_delete.Visible = false;
                btn_cancel.Visible = true;
                btn_cancel.Location = btn_modify.Location;
                btn_add.Tag = "保存";
                btn_add.Image = Properties.Resources.UserForm_btnsave001;
            }
            else
            {
                if (!CheckInput()) return;
                
                string strPhoneNum = textEdit_PhoneNumber.Text.Trim(); 
                string strTaxiNo = textEdit_TaxiNo.Text.Trim();
                string strTaxiType = textEdit_TaxiType.Text.Trim();
                string strImei = textEdit_Imei.Text.Trim();                
                string strRemark = textEdit_remark.Text.Trim();
                string strState = comBox_statelist.Properties.Items[
                    comBox_statelist.SelectedIndex].Value.ToString();

                if (MainForm.PositionService.TaxiExistsPhoneNum(strPhoneNum))
                {
                    XtraMessageBox.Show("手机号码已被使用，请输入其他帐号！");
                    textEdit_PhoneNumber.Focus();
                    return;
                }

                try
                {
                    TaxiInfo taxi = new TaxiInfo()
                    {                        
                        PhoneNumber = strPhoneNum,                                               
                        TaxiNo = strTaxiNo,
                        TaxiType = strTaxiType,
                        Imei = strImei,
                        Remark = strRemark,
                        State = strState
                    };
                    if (MainForm.PositionService.TaxiAdd(taxi))
                    {
                        XtraMessageBox.Show("添加成功");
                        gridControl1.Enabled = true;
                        btn_select.Enabled = true;
                        btn_delete.Visible = true;
                        btn_modify.Visible = true;
                        btn_cancel.Visible = false;
                        btn_add.Enabled = true;

                        textEdit_PhoneNumber.Enabled = false;
                        textEdit_Imei.Enabled = false;
                        textEdit_TaxiNo.Enabled = false;
                        textEdit_TaxiType.Enabled = false;
                        textEdit_remark.Enabled = false;
                        comBox_statelist.Enabled = false;

                        btn_add.Tag = "新增";
                        btn_add.Image = Properties.Resources.UserForm_btnadd001;
                        _isAdd = true;
                        _thread = new Thread(BindGrid);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("添加失败");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }


                //taxi.TaxiType=
            }

        }

        private string _oldPhoneNumber = "";

        private void simpleButton_modify_Click(object sender, EventArgs e)
        {
            if (label_id.Text == string.Empty)
            {
                XtraMessageBox.Show("请选择要修改的司机！");
                return;
            }
            if (btn_modify.Tag.ToString() == "修改")
            {

                _oldPhoneNumber = textEdit_PhoneNumber.Text;
                textEdit_PhoneNumber.Enabled = true;
                textEdit_Imei.Enabled = true;
                textEdit_TaxiNo.Enabled = true;
                textEdit_TaxiType.Enabled = true;
                comBox_statelist.Enabled = true;
                textEdit_remark.Enabled = true;

                gridControl1.Enabled = false;
                btn_select.Enabled = false;
                btn_delete.Visible = false;
                btn_cancel.Visible = true;
                btn_cancel.Location = btn_modify.Location;
                btn_modify.Location = btn_add.Location;
                btn_add.Visible = false;
                btn_modify.Tag = "保存";
                btn_modify.Image = Properties.Resources.UserForm_btnsave001;
            }
            else
            {
                if (!CheckInput()) return;
               
                int id = int.Parse(label_id.Text);
                 string strPhoneNum = textEdit_PhoneNumber.Text.Trim(); 
                string strTaxiNo = textEdit_TaxiNo.Text.Trim();
                string strTaxiType = textEdit_TaxiType.Text.Trim();
                string strImei = textEdit_Imei.Text.Trim();                
                string strRemark = textEdit_remark.Text.Trim();
                string strState = comBox_statelist.Properties.Items[
                 comBox_statelist.SelectedIndex].Value.ToString();
                if (strPhoneNum!=_oldPhoneNumber)
                {
                    bool exist = MainForm.PositionService.TaxiExistsPhoneNum(
                        strPhoneNum);
                    if (exist)
                    {
                        XtraMessageBox.Show("该手机号码已被使用，请核对！");
                        return;
                    }
                }
                TaxiInfo taxi = new TaxiInfo()
                {
                    Id = id,
                    PhoneNumber = strPhoneNum,
                    TaxiNo = strTaxiNo,
                    TaxiType = strTaxiType,
                    Imei = strImei,
                    Remark = strRemark,
                    State = strState
                };

                try
                {
                    if (MainForm.PositionService.TaxiUpdate(taxi))
                    {
                        XtraMessageBox.Show("修改成功！");

                        gridControl1.Enabled = true;
                        btn_select.Enabled = true;
                        btn_delete.Visible = true;
                        btn_add.Visible = true;
                        btn_modify.Location = btn_cancel.Location;
                        btn_cancel.Visible = false;
                        btn_modify.Tag = "修改";
                        btn_modify.Image = Properties.Resources.UserForm_btnmodify001;

 
                        textEdit_PhoneNumber.Enabled = false;
                        textEdit_Imei.Enabled = false;
                        textEdit_TaxiNo.Enabled = false;
                        textEdit_TaxiType.Enabled = false;
                        textEdit_remark.Enabled = false;
                        comBox_statelist.Enabled = false;
                         
                        //BindGrid();
                        _thread = new Thread(BindGrid);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("修改失败！");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }
            }
        }

        private void simpleButton_delete_Click(object sender, EventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);
            string id;
            if (row == null)
            {
                XtraMessageBox.Show("请选择要删除的司机！");
                return;
            }
            id = row["id"].ToString();
            string phoneNum = row["PhoneNumber"].ToString();
            if (XtraMessageBox.Show("确认删除手机号为【" + phoneNum 
                + "】的记录吗？", "警告", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    if (MainForm.PositionService.DriverDelete(int.Parse(id)))
                    {
                        XtraMessageBox.Show("删除成功！");
                        _thread = new Thread(BindGrid);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("删除失败！");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                }

            }
        }

        private void simpleButton_Select_Click(object sender, EventArgs e)
        {
            gridView1.GroupPanelText = "数据加载中...";
            btn_select.Enabled = false;
            _thread = new Thread(BindGrid);
            _thread.Start();
        }

        private void simpleButton_cancle_Click(object sender, EventArgs e)
        {
            gridView1_RowClick(null, null);
            gridControl1.Enabled = true;
            btn_select.Enabled = true;
            btn_delete.Visible = true;
            btn_cancel.Visible = false;
            btn_add.Visible = true;
            btn_add.Tag = "新增";
            btn_add.Image = Properties.Resources.UserForm_btnadd001;
            btn_modify.Visible = true;
            btn_modify.Tag = "修改";
            btn_modify.Image = Properties.Resources.UserForm_btnmodify001;
            btn_modify.Location = btn_cancel.Location;

            textEdit_PhoneNumber.Enabled = false;
            textEdit_Imei.Enabled = false;
            textEdit_TaxiNo.Enabled = false;
          
            comBox_statelist.Enabled = false;
            textEdit_remark.Enabled = false;
          
        }

        public void ClearInputControl()
        {
            BeginInvoke(new MethodInvoker(() =>
                {
                    label_id.Text = "";
                    textEdit_PhoneNumber.Text = "";
                    textEdit_Imei.Text = "";
                    textEdit_TaxiNo.Text = "";
                    textEdit_TaxiType.Text = "";
                    textEdit_remark.Text = "";
                    comBox_statelist.SelectedIndex = 0;
                    
                }));            
        }
         
        private bool CheckInput()
        {
           
            string strTaxiNo = textEdit_TaxiNo.Text.Trim();
             string strPhoneNum = textEdit_PhoneNumber.Text.Trim();
            string strTaxiType = textEdit_TaxiType.Text.Trim();
            string strImei = textEdit_Imei.Text;

            if (strTaxiNo == "")
            {
                XtraMessageBox.Show("车辆牌照不能为空！");
                textEdit_TaxiNo.Focus();
                return false;
            }
            if (Encoding.GetEncoding("GBK").GetBytes(strTaxiNo).Length > 20)
            {
                XtraMessageBox.Show("车辆牌照长度太长！");
                textEdit_TaxiNo.Focus();
                return false;
            }
            //if (strTaxiType == "")
            //{
            //    XtraMessageBox.Show("车辆型号不能为空！");
            //    textEdit_TaxiType.Focus();
            //    return false;
            //}
            if (Encoding.GetEncoding("GBK").GetBytes(strTaxiType).Length > 20)
            {
                XtraMessageBox.Show("车辆型号长度太长！");
                textEdit_TaxiType.Focus();
                return false;
            }
            if (strPhoneNum=="")
            {
                XtraMessageBox.Show("手机号码不能为空！");
                textEdit_PhoneNumber.Focus();
                return false;
            }


            if (strPhoneNum.Length > 15)
            {
                XtraMessageBox.Show("手机号码输入长度过大！");
                textEdit_PhoneNumber.Focus();
                return false;
            }
            
            if (strImei.Length > 25)
            {
                XtraMessageBox.Show("Imei长度过大，最多为25位！");
                textEdit_Imei.Focus();
                return false;
            }
     
            return true;
        }

        #region  窗体控件操作、效果
        Point _mouseOff;
        bool _leftFlag;
        private void Taxi_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Taxi_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Taxi_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }
        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Default;
        }
        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }

        #endregion

        private void btn_exportToExcel_Click(object sender, EventArgs e)
        {
            saveFileDialog1.FileName = "司机信息列表";
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                gridView1.ExportToXls(saveFileDialog1.FileName);
                XtraMessageBox.Show("Excel导出完成！");
            }
        }

        private void From_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_thread != null)
            {
                _thread.Abort();
            }
        }

        

        private void textEdit_condition_KeyPress(object sender, KeyPressEventArgs e)
        {

            if ((Keys)e.KeyChar == Keys.Enter)
            {
                simpleButton_Select_Click(null, null);
            }

        }
         
    }
}